package com.example.shiro.common.util;

import org.apache.shiro.codec.Hex;

import java.security.MessageDigest;
import java.util.Random;

/**
 * @auther 严旭平
 * @date 2020/4/2410:46
 * @Description MD5随机加密加盐工具类
 */
public class MD5Utils {

    /**
     * 私有构造方法
     */
    private MD5Utils(){}

    /**
     * 获取加密后的字符串
     * @param password 欲加密的密码
     * @return 生成的密码字符串
     */
    public static String getSaltMD5(  String password ) {
        // 生成一个16位的随机数
        Random random = new Random();
        StringBuilder sBuilder = new StringBuilder(16);
        sBuilder.append(random.nextInt(99999999)).append(random.nextInt(99999999));
        int len = sBuilder.length();
        if (len < 16) {
            for (int i = 0; i < 16 - len; i++) {
                sBuilder.append("0");
            }
        }
        // 生成最终的加密盐
        String Salt = sBuilder.toString();
        password = md5Hex(password + Salt);
        char[] cs = new char[48];
        for (int i = 0; i < 48; i += 3) {
            cs[i] = password.charAt(i / 3 * 2);
            char c = Salt.charAt(i / 3);
            cs[i + 1] = c;
            cs[i + 2] = password.charAt(i / 3 * 2 + 1);
        }
        return String.valueOf(cs);
    }

    /**
     *验证密码
     * @param password 欲验证的密码
     * @param saltPassword 数据库存储的字段
     * @return
     */
    public static Boolean verify( String password, String saltPassword ) {
        char[] cs1 = new char[32];
        char[] cs2 = new char[16];
        for (int i = 0; i < 48; i += 3) {
            cs1[i / 3 * 2] = saltPassword.charAt(i);
            cs1[i / 3 * 2 + 1] = saltPassword.charAt(i + 2);
            cs2[i / 3] = saltPassword.charAt(i + 1);
        }
        String Salt = new String(cs2);
        return md5Hex(password + Salt ).equals( String.valueOf(cs1) );
    }


    /**
     * 用于密码加盐
     * @param str
     * @return
     */
    private static String md5Hex(String str) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(str.getBytes());
            return new String(new Hex().encode(digest));
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.toString());
            return "";
        }
    }


}
